/*
 * Copyright Notice ====================================================
 * This file contains proprietary information of Hewlett-Packard Co.
 * Copying or reproduction without prior written approval is prohibited.
 * Copyright (c) 2013 All rights reserved. =============================
 */

package com.hp.ecs.sonar.email;

import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.hp.ecs.sonar.util.Violation;

public class MailSender {

	private static final Log LOG = LogFactory.getLog(MailSender.class);

	public static void sendTextMail(MailSenderInfo mailInfo) {
		MyAuthenticator authenticator = null;
		Properties pro = mailInfo.getProperties();
		if (mailInfo.isValidate()) {
			authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
		}
		Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
		try {
			Message mailMessage = new MimeMessage(sendMailSession);
			Address from = new InternetAddress(mailInfo.getFromAddress());
			mailMessage.setFrom(from);
			setRecipient(mailInfo.getToAddress(), mailMessage);
			mailMessage.setSubject(mailInfo.getSubject());
			mailMessage.setSentDate(new Date());
			String mailContent = mailInfo.getContent();
			mailMessage.setText(mailContent);
			Transport.send(mailMessage);
		} catch (MessagingException ex) {
			LOG.error(ex, ex);
		}
	}

	public static void setRecipient(String toAddress, Message mailMessage) throws AddressException, MessagingException {
		for (String address : toAddress.split("[\\;\\,]")) {
			address = address.trim();
			if (address.indexOf('@') > 0) {
				Address to = new InternetAddress(address.trim());
				mailMessage.addRecipient(Message.RecipientType.TO, to);
			}
		}
	}

	public static String toMailContent(List<Violation> violations) {
		Collections.sort(violations, new Comparator<Violation>() {

			public int compare(Violation o1, Violation o2) {
				if (o1.getLevel().equals(o2.getLevel())) {
					if (o1.getFile().equals(o2.getFile())) {
						if (o1.getLine() == null) {
							return -1;
						}
						return o1.getLine().compareTo(o2.getLine());
					} else {
						return o1.getFile().compareTo(o2.getFile());
					}
				} else {
					return o1.getLevel().ordinal() > o2.getLevel().ordinal() ? 1 : -1;
				}
			}

		});
		StringBuilder sb = new StringBuilder();
		for (Violation v : violations) {
			sb.append(v).append("\n\n");
		}
		return sb.toString();
	}

	private static String host;

	private static String port;

	private static String userName;

	private static String password;

	private static String from;

	public static void send(String toAddress, String title, String content) {
		MailSenderInfo mailInfo = new MailSenderInfo();
		mailInfo.setMailServerHost(host);
		mailInfo.setMailServerPort(port);
		mailInfo.setValidate(true);
		mailInfo.setUserName(userName);
		mailInfo.setPassword(password);
		mailInfo.setFromAddress(from);
		mailInfo.setToAddress(toAddress);
		mailInfo.setSubject("[sonar]" + title);
		mailInfo.setContent(content);
		MailSender.sendTextMail(mailInfo);
	}

	public static void setConfig(String host, String port, String userName, String password, String from) {
		MailSender.host = host;
		MailSender.port = port;
		MailSender.userName = userName;
		MailSender.password = password;
		MailSender.from = from;
	}

	public static boolean configured() {
		return !"nobody@hp.com".equals(userName) || !"password".equals(password);
	}
}
